/*
 * @Date 2020-03-23
 * @Author gt333
 * @description 支付宝webview jsdk
 * 支付宝jsdk: https://myjsapi.alipay.com/alipayjsapi/index.html
 * 支付宝小程序jsdk: https://opendocs.alipay.com/mini/component/web-view
 * ====
 * @update_date
 * @update_author
 * @update_desc
 * ====
 */

const miniHomePage = '/pages/invoice/invList/invList'

/**
 * @func 统一处理调用支付宝API 回调
 * @param {Object} res 支付宝API返回结果
 * @param {Function} success 成功回调
 * @param {Function} fail 失败回调
 */
function globalCallback (res, success, fail) {
  const { code } = res
  if (code === 10 || code === 11) {
    fail && fail(code)
  } else {
    success(code)
  }
}

/**
 * 支付宝APP H5方法，非小程序调用 （废弃）
 * @func 扫一扫
 * @param {Object} param0
 */
// export const scanQRCode = ({
//   scanType,
//   success = () => undefined,
//   fail = () => undefined
// }) => {
//   const type = {
//     qrCode: "qr",
//     barCode: "bar"
//   };
//   ap.scan(
//     {
//       type: type[scanType]
//     },
//     function(res) {
//       callback(res, success, fail);
//     }
//   );
// };

/**
 * 支付宝APP H5方法，非小程序调用 （废弃）
 * 选择图片
 * @param {Object} param0
 */
// export const chooseImage = ({
//   count = 9,
//   sizeType = ["original", "compressed"],
//   sourceType = ["camera", "album"]
// }) => {
//   ap.chooseImage({ count, sourceType }, function(res) {
//     callback(
//       res,
//       () => {
//         const { apFilePaths } = res;
//         success(res);
//       },
//       fail
//     );
//   });
// };

// postmessage 统一监听

const onMessage = (success, fail) => {
  // if (!window.NUOMY.onMessage) {
  window.NUOMY.onMessage = function (res) {
    if (res && res instanceof Object) {
      try {
        for (var keys in res) {
          if (
            String(keys)
              .toLocaleLowerCase()
              .indexOf('success') > -1
          ) {
            success(res[keys])
          }
          if (
            String(keys)
              .toLocaleLowerCase()
              .indexOf('fail') > -1
          ) {
            fail(res[keys])
          }
        }
      } catch (error) {}
    } else {
      console.warn('小程序传入参数非对象，拒绝访问')
      fail({ err: '小程序传入参数非对象，拒绝访问' })
    }
  }
  // }
}

/**
 * 获取小程序环境
 * @param {Function} callback
 */
export const getEnv = callback => {
  window.NUOMY.getEnv(callback)
}

/**
 * 支付宝扫码 postmessage 处理
 * @param {*} param0
 */
export const scanQRCode = ({
  scanType,
  success = () => undefined,
  fail = () => undefined
}) => {
  const type = {
    qrCode: 'qr',
    barCode: 'bar'
  }
  onMessage(success, fail)
  window.NUOMY.postMessage({ eventName: 'openScan' })
}

/**
 * @func 获取支付宝发票抬头 postmessage 处理
 * @param {*} param0
 */
export const chooseInvoiceTitle = ({
  success = () => undefined,
  fail = () => undefined
}) => {
  onMessage(success, fail)
  window.NUOMY.postMessage({ eventName: 'chooseInvoiceTitle' })
}

/**
 * @func 获取支付宝授权 postmessage 处理
 * @param {*} param0
 */
export const getAuthCode = ({
  success = () => undefined,
  fail = () => undefined
}) => {
  onMessage(success, fail)
  window.NUOMY.postMessage({ eventName: 'getAuthCode' })
}

/**
 * desc: https://opendocs.alipay.com/mini/api/navigatetoalipaypage
 * 跳转支付宝内置小程序页面 postmessage 处理
 * @param {*} param0
 */
export const navigateToAlipayPage = ({
  appCode = null,
  appParams = null,
  path = '',
  extraParam = null,
  success = () => undefined,
  fail = () => undefined
}) => {
  onMessage(success, fail)
  if (path) {
    window.NUOMY.postMessage({
      eventName: 'navigateToAlipayPage',
      data: {
        path,
        appCode,
        appParams
      },
      extraParam
    })
  } else {
    fail({ err: '请输入跳转地址' })
  }
}

/**
 * webview 跳转小程序
 * @param {} param0
 */
export const navigateToMiniProgram = ({
  appId = '',
  path = '',
  extraData = null,
  success = () => undefined,
  fail = () => undefined
}) => {
  onMessage(success, fail)
  if (path && appId) {
    window.NUOMY.postMessage({
      eventName: 'navigateToMiniProgram',
      data: {
        path,
        appId
      },
      extraData
    })
  } else {
    fail({ err: '请输入跳转地址path或者appId' })
  }
}

/**
 * @func 支付宝实名认证
 */
export const startAPVerify = ({
  certno = '',
  certname = '',
  extraData = null,
  success = () => undefined,
  fail = () => undefined
}) => {
  onMessage(success, fail)
  if (certno && certname) {
    window.NUOMY.postMessage({
      eventName: 'startAPVerify',
      data: {
        certno,
        certname
      },
      extraData
    })
  } else {
    fail({ err: '请输入实名认证用户姓名和身份证号码' })
  }
}

/**
 * 支付宝APP 小程序调用
 * 选择图片
 * @param {*} param0
 */
export const chooseImage = ({
  count = 1, // 默认1
  sizeType = ['original', 'compressed'],
  sourceType = ['camera', 'album'],
  success = () => undefined,
  fail = () => undefined,
  complete = () => undefined
}) => {
  window.NUOMY.chooseImage({
    sourceType,
    count,
    success,
    fail,
    complete
  })
}

/**
 * webview 返回
 */
export const navigateBack = () => {
  window.NUOMY.navigateBack({
    fail (err) {
      // 支付宝小程序返回失败执行此方法。统一回到小程序首页
      // PS:此处区别与微信小程序,微信小程序返回失败也不会执行fail
      window.NUOMY.switchTab({
        url: miniHomePage,
        fail (es) {
          // 再失败就没救了
          console.log('err', es)
        }
      })
    }
  })
}

/**
 * webview tabbar 跳转
 * @param {*} param0
 */
export const switchTab = ({ url = miniHomePage, success, fail, complete }) => {
  window.NUOMY.switchTab({
    url,
    success,
    complete,
    fail (es) {
      // 失败就没救了
      console.log('err', es)
    }
  })
}

/**
 * webview 跳转页面
 * @param {*} param0
 */
export const navigateTo = ({ url, success, fail, complete }) => {
  window.NUOMY.navigateTo({
    url,
    success,
    fail,
    complete
  })
}

/**
 * webview 重定向
 * @param {Object} param
 */
export const redirectTo = ({ url, success, fail, complete }) => {
  window.NUOMY.redirectTo({
    url,
    fail,
    success,
    complete
  })
}

/**
 * webview 关闭当前所有页面，跳转到应用内的某个指定页面。
 * @param {Object} param
 */
export const reLaunch = ({ url, success, fail, complete }) => {
  window.NUOMY.reLaunch({
    url,
    success,
    fail,
    complete
  })
}
/**
 * @func 支付宝支付
 * @param {Object} param0
 */
export const tradePay = ({
  tradeNO = '',
  payStr = '',
  success = () => undefined,
  fail = () => undefined
}) => {
  const payNo = payStr || tradeNO
  if (!payNo) {
    fail()
    console.warn('请输入支付交易号')
    return
  }
  window.NUOMY.tradePay({
    tradeNO: payNo,
    success,
    fail
  })
}

/**
 * @func 支付宝定位
 * @param {Object} param0
 */
export const getLocation = ({
  type = 0,
  cacheTimeout = 30,
  success = () => undefined,
  fail = () => undefined
}) => {
  window.NUOMY.getLocation({
    type,
    cacheTimeout,
    success,
    fail
  })
}
